package com.jz.netthings.netty.decode;

import com.jz.netthings.netty.support.Attributes;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.HashMap;
import java.util.List;

/**
 * 负责解码采浆机上传的数据库文件
 */
public class NettyZxdcLogDecoder extends ByteToMessageDecoder {


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        String s = byteBuf.toString(CharsetUtil.US_ASCII);
        int length = byteBuf.readableBytes();
//        System.out.println("log 长度：【"+length+"】");

        if (length == 4){
            int i = byteBuf.readInt();
            if (i == Attributes.LOG_CODE){
                System.out.println(" i = "+i);
                list.add(i);
                byteBuf.skipBytes(byteBuf.readableBytes());
            }else{
                System.out.println(" i = "+i);
                byteBuf.resetReaderIndex();
                return;
            }
        }else if(length < 4){
            //证明消息长度都不够
            byteBuf.resetReaderIndex();
            return;
        }else if(length >= 54 && length < 90 && s.indexOf("{log}") > 0){
            //是文件名
            System.out.println("长度：【"+length+"】：" + s);
            list.add(s);
            byteBuf.skipBytes(byteBuf.readableBytes());
        }/*else if(length == 8){
            int i = byteBuf.readInt();
            System.out.println(" iiiii = "+i);
            if (i == Attributes.LOG_CODE){
                int j =  byteBuf.readInt();
                Integer[] ii = new Integer[2];
                ii[0] = i;
                ii[1] = j;
                list.add(ii);
            }
            byteBuf.resetReaderIndex();
            byteBuf.skipBytes(byteBuf.readableBytes());
        }*/else {
            int i = byteBuf.readInt();
            System.out.println(" 数据长度 = "+i);
            if (length == (i + 4)){
                //证明是所有数据
                byte[] data = new byte[i];
                byteBuf.readBytes(data);

                list.add(data);
                byteBuf.resetReaderIndex();
                byteBuf.skipBytes(byteBuf.readableBytes());
            }else {
                byteBuf.resetReaderIndex();
                return;
            }
        }

    }
}
